<template>
  <div class="table_header">
    <slot name="headerTitle">
      <span v-if="title" class="table_header_title" :title="title">
        {{ title }}
      </span>
      <slot name="titleTip"></slot>
    </slot>
    <div class="table_header_action" :style="actionStyle">
      <slot name="searchBefore"></slot>

      <!-- project -->
      <op-select
        v-if="showProject"
        :key="projectid"
        :size="size"
        prop="project"
        v-model="projectid"
        v-bind="projectConfigNew"
        @itemEvent="handleSelectChange"
      ></op-select>

      <!-- status -->
      <op-select
        v-if="showStatus"
        :size="size"
        prop="status"
        v-model="status"
        v-bind="statusConfigNew"
        @itemEvent="handleSelectChange"
      ></op-select>

      <!-- orgid -->
      <op-select
        v-if="showOrgid && isAdmin === '1'"
        :size="size"
        prop="orgid"
        v-model="orgid"
        v-bind="orgidConfigNew"
        @itemEvent="handleSelectChange"
      ></op-select>

      <!-- time -->
      <op-date
        v-if="showDate"
        :size="size"
        :initDate="initDate"
        v-model="date"
        v-bind="dateConfigNew"
        @itemEvent="dateChange"
      ></op-date>

      <el-input
        v-if="showSearch"
        class="search_input"
        clearable
        :size="size"
        v-model="searchKey"
        :placeholder="searchPlaceholder"
        @change="handleSearchChange"
      >
        <template #append>
          <el-button :size="size" :icon="Search" @click="handleSearchChange" />
        </template>
      </el-input>
      <table-export
        v-if="showExport"
        :key="tableList"
        :tableList="tableList"
        :exportInfo="exportInfo"
        :showChangeHeader="showChangeHeader"
        :exportTitle="exportTitle"
        :showPagination="showPagination"
        @columnChange="data => emits('columnChange', data)"
      >
      </table-export>

      <table-data-export
        v-if="showDataExport"
        :key="tableList"
        :tableList="tableList"
        :exportInfo="exportInfo"
      >
      </table-data-export>
      <slot name="searchAfter"></slot>

      <button-list
        v-if="buttonList?.length"
        :size="size"
        :buttonList="buttonList"
        @buttonClick="data => emits('buttonClick', data)"
      ></button-list>
    </div>
  </div>
</template>
<script setup>
import moment from 'moment';

import { Search } from '@element-plus/icons-vue';
import TableExport from './TableExport.vue';
import TableDataExport from './TableDataExport.vue';
import ButtonList from '../../button/ButtonList.vue';

const props = defineProps({
  title: {
    type: String,
    default: '',
  },
  showSearch: {
    type: Boolean,
    default: true,
  },
  showExport: {
    type: Boolean,
    default: true,
  },
  showDataExport: {
    type: Boolean,
    default: false,
  },
  searchPlaceholder: {
    type: String,
    default: 'Search',
  },
  size: {
    type: String,
    default: 'small',
  },
  buttonList: {
    type: Array,
    default: () => [],
  },
  showProject: {
    // 是否展示project
    type: Boolean,
    default: false,
  },
  projectConfig: {
    // project配置
    type: Object,
    default: () => ({}),
  },
  showStatus: {
    // 是否展示status
    type: Boolean,
    default: false,
  },
  statusConfig: {
    // status配置
    type: Object,
    default: () => ({}),
  },
  showOrgid: {
    // 是否展示orgid
    type: Boolean,
    default: false,
  },
  orgidConfig: {
    // orgid配置
    type: Object,
    default: () => ({}),
  },
  showDate: {
    // 是否展示时间
    type: Boolean,
    default: false,
  },
  dateConfig: {
    // 时间配置
    type: Object,
    default: () => ({
      initValue: null,
      initValueType: '',
      startKey: 'startDate',
      endKey: 'endDate',
    }),
  },
  tableList: {
    type: Array,
    default: () => [],
  },
  exportInfo: {
    type: Object,
    default: () => ({}),
  },
  actionStyle: {
    type: [String, Object],
  },
  // 是否展示自定义设置表头
  showChangeHeader: {
    type: Boolean,
    default: true,
  },
  // 导出图片后面文字
  exportTitle: {
    type: String,
    default: '',
  },
  showPagination: {
    type: Boolean,
  },
});

const projectConfigNew = computed(() => {
  return {
    filterKey: {
      label: 'name',
      value: 'id',
    },
    placeholder: 'Project',
    style: 'width: 160px',
    ...props.projectConfig,
  };
});

const statusConfigNew = computed(() => {
  return {
    filterKey: {
      label: 'name',
      value: 'id',
    },
    placeholder: 'Status',
    style: 'width: 160px',
    ...props.statusConfig,
  };
});

const orgidConfigNew = ref({
  size: 'small',
  style: { width: '160px', 'margin-right': '10px' },
  requestUrl: '/account/getOrgList',
  filterKey: {
    label: 'name',
    value: 'id',
  },
  ...props.orgidConfig,
  cb: res => {
    if (res?.length) {
      orgid.value = res[0].id;
      emits('resetPageNum', 1, {
        eventName: 'change',
        value: orgid.value,
        prop: 'orgid',
        options: res,
      });
    }
  },
});

const dateConfigNew = computed(() => {
  return {
    type: 'daterange',
    style: 'width: 180px; flex-grow: 0;',
    format: 'DD/MM/YYYY',
    valueFormat: 'YYYY-MM-DD',
    ...props.dateConfig,
  };
});

const emits = defineEmits(['buttonClick', 'resetPageNum', 'columnChange']);

const searchKey = ref('');
const projectid = ref('');
const status = ref('');
const orgid = ref('');
const date = ref();
const initDate = ref();
const initParams = ref({}); // 默认值
const isAdmin = ref('');

const searchParams = computed(() => {
  let obj = {
    ...initParams.value,
  };
  if (props.showSearch) obj.searchKey = searchKey.value ? searchKey.value.trim() : '';
  if (props.showProject) obj.projectid = projectid.value || '';
  if (props.showStatus) obj.status = status.value || '';
  if (props.showOrgid) obj.orgid = orgid.value || '';
  if (props.showDate) {
    obj[props?.dateConfig?.startKey || 'startDate'] =
      date.value && date.value[0] ? date.value[0] : '';
    obj[props?.dateConfig?.endKey || 'endDate'] = date.value && date.value[1] ? date.value[1] : '';
  }
  return obj;
});

onMounted(() => {
  isAdmin.value = sessionStorage.getItem('isAdmin');
  if (isAdmin.value !== '1' && props.showOrgid) {
    orgid.value = sessionStorage.getItem('orgid');
    emits('resetPageNum', 1, { eventName: 'change', value: orgid.value, prop: 'orgid' });
  }
});

// select change
function handleSelectChange(data) {
  const { eventName } = data;
  if (eventName === 'change') handleSearchChange(data);
}

function handleSearchChange(data) {
  emits('resetPageNum', 1, data);
}

// 设置查询条件
function initFormData(val) {
  initParams.value = { ...initParams.value, ...val };
}

// 初始时间
function initDateFn(initType, type) {
  if (typeof initType == 'number') {
    date.value = [
      moment().subtract(initType, 'month').format('YYYY-MM-DD'),
      moment().format('YYYY-MM-DD'),
    ];
  } else {
  }
  initDate.value = [...date.value];
}
// 时间change
function dateChange(data) {
  const { value } = data;
  date.value = value;
  emits('resetPageNum', 1, { prop: 'date', value, eventName: 'change' });
}

watch(
  () => props.dateConfig,
  val => {
    const { type, initValueType, initValue } = props.dateConfig;
    if (initValueType) initDateFn(initValueType, type);
    if (initValue) {
      if (typeof initValue == 'string') {
        date.value = initValue.format('YYYY-MM-DD');
        initDate.value = date.value;
      } else {
        date.value = [
          moment(initValue[0]).format('YYYY-MM-DD'),
          moment(initValue[1]).format('YYYY-MM-DD'),
        ];
        initDate.value = [...date.value];
      }
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

// 设置状态默认值
watch(
  () => props.statusConfig.initValue,
  val => {
    if (val) status.value = val;
  },
  {
    immediate: true,
  }
);

defineExpose({
  initFormData,
  searchParams,
});
</script>
<style lang="scss" scoped>
.table_header {
  padding-bottom: 8px;
  display: flex;
  justify-content: space-between;
}

.table_header_title {
  font-size: 16px;
  margin-right: 10px;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.table_header_action {
  margin-left: auto;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  .search_input {
    width: 200px;
  }
  :deep() {
    > div {
      margin-right: 10px;
    }
    > div:last-of-type {
      margin-right: 0;
    }
  }
}
</style>
